<template>
  <div class="main">
    <!-- 搜索框 -->
    <div class="search-bar">
      <el-row :gutter="20" class="search-row">
        <div class="date-filter">
          <!-- 使用Element UI的el-date-picker替换原来的input -->
          <el-date-picker
            v-model="search.startDate"
            type="date"
            placeholder="开始日期"
            class="inputselect"
            size="large"
          />
          <span>至</span>
          <el-date-picker
            v-model="search.endDate"
            type="date"
            placeholder="结束日期"
            class="inputselect"
            size="large"
          />
        </div>
        <el-col :span="3">
          <el-select
            class="camera-filter"
            v-model="search.cameraName"
            placeholder="请选择摄像头"
            size="large"
            clearable
            :filterable="true"
          >
            <el-option
              v-for="item in cameraOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-select
            class="type-filter"
            v-model="search.type"
            placeholder="请选择警告类型"
            size="large"
            clearable
            :filterable="true"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" @click="filterData" class="search-button">搜索</el-button>
        </el-col>
      </el-row>
    </div>
    
    <!-- 表格 -->
    <el-table
      class="table"
      :data="pagedAlarmData"
      border="false"
      style="width: 100%;"
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
    >
      <el-table-column
        prop="time"
        label="时间"
        width="180"
        :formatter="formatTime"
      />
      <el-table-column prop="cameraName" label="摄像头" width="180" />
      <el-table-column prop="message" label="警告信息" />
      <el-table-column prop="type" label="警告类型" width="180"/>
      <el-table-column prop="mid" label="中间件" width="180"/>
      <el-table-column label="图片" width="180">
        <template #default="{ row }">
          <el-image
            style="width: 100px; height: 100px; z-index: 9999"
            :src="row.image"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="[row.image]"
            :initial-index="4"
            fit="cover"
            :preview-teleported="true"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="primary" @click="dialogVisible = true; cameraRtsp = row.cameraRtsp;">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 自定义分页 -->
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
  </div>

  <!-- 实时视频弹窗 -->
  <el-dialog
    title="实时视频"
    v-model="dialogVisible"
    width="30%"
    :before-close="handleClose"
  >
    <Rtsp :customRtsp="cameraRtsp" />
  </el-dialog>
</template>

<script setup>
import { reqAlarmData } from "@/api/alarm/index.js";
import Rtsp from '@/components/RealTimeVideo/index.vue'
import { watch, ref, onMounted, computed } from 'vue';
import dayjs from 'dayjs';

import useOperationStore from '@/store/operation.js'

// 获取操作的 store 实例
const operationStore = useOperationStore()

// 使用 Pinia store 中的状态
const data = computed(() => operationStore.data) // 获取业务数据
const index = computed(() => operationStore.index) // 获取选中的业务

const alarmData = ref([]);  // 存储从 API 获取的数据
const filteredAlarmData = ref([]);  // 存储筛选后的数据

const cameraOptions = ref([]);  // 存储摄像头选项
const typeOptions = ref([]);  // 存储警告类型选项

const search = ref({
  startDate: '',
  endDate: '',
  cameraName: '',
  type: [
    { label: '人脸识别', value: '人脸识别' },
    { label: '车辆识别', value: '车辆识别' },
    { label: '人员聚集', value: '人员聚集' },
    { label: '人员侵入', value: '人员侵入' },
    { label: '车辆侵入', value: '车辆侵入' },
    { label: '车辆聚集', value: '车辆聚集' },
  ]
});

const dialogVisible = ref(false);
const operationId = ref(null);
const cameraRtsp = ref('');

const pageSize = ref(10);  // 每页显示的条数
const currentPage = ref(1);  // 当前页码

// 关闭对话框的处理函数
const handleClose = () => {
  dialogVisible.value = false;
};

// 在页面加载时请求警告数据
onMounted(async () => {
  await getData();
});

// 监听选中的业务变化，重新加载数据
watch(index, async () => {
  await getData();
});

// 获取数据
const getData = async () => {
  const operationId = data.value[index.value].id

  const response = await reqAlarmData(operationId);
  if (response.code === 0) {
    alarmData.value = response.data.records.map(item => ({
      time: item.time,
      cameraName: item.cameraName,
      message: item.message,
      image: item.image,
      operationId: item.id,
      cameraRtsp: item.cameraRtsp,
      type: item.type,
      mid: item.mid,
    }));

    // 动态设置摄像头和警告类型的选项
    cameraOptions.value = Array.from(new Set(response.data.records.map(item => item.cameraName)))
      .map(camera => ({ label: camera, value: camera }));
    typeOptions.value = Array.from(new Set(response.data.records.map(item => item.type)))
      .map(type => ({ label: type, value: type }));

    // 默认显示所有数据
    filteredAlarmData.value = alarmData.value;
  } else {
    console.error('获取数据失败');
  }
};

// 格式化时间为易读格式
const formatTime = (row, column, cellValue) => {
  return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss');
};

// 筛选数据
const filterData = () => {
  let filteredData = alarmData.value;

  if (search.value.startDate && search.value.endDate) {
    const startTime = search.value.startDate;
    const endTime = search.value.endDate;
    const startTimestamp = new Date(startTime).getTime();
    const endTimestamp = new Date(endTime).getTime();
    filteredData = filteredData.filter(item => {
      const itemTime = new Date(item.time).getTime();
      return itemTime >= startTimestamp && itemTime <= endTimestamp;
    });
  }

  if (search.value.cameraName) {
    filteredData = filteredData.filter(item => item.cameraName === search.value.cameraName);
  }

  if (search.value.type) {
    filteredData = filteredData.filter(item => item.type === search.value.type);
  }

  filteredAlarmData.value = filteredData;
};

// 处理上一页按钮
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

// 处理下一页按钮
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
};

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(filteredAlarmData.value.length / pageSize.value);
});

// 计算当前页显示的数据
const pagedAlarmData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  return filteredAlarmData.value.slice(startIndex, startIndex + pageSize.value);
});
</script>

<style scoped>
.main {
  margin: 10px;
  height: 100%;
  width: 99%;
  
  .table {
    border-radius: 5px;
    height: 85%;
    overflow-y: auto;
  }
  .search-bar {
    width: 100%;
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
    .search-row {
      display: flex;
      justify-content: flex-end;
    }
    .date-filter {
      display: flex;
      align-items: center;
      gap: 20px;
      .inputselect {
        width: 200px;
        height: 40px;
        font-size: 17px;
        border-radius: 5px;
        border: 0.5px solid rgb(219, 219, 219);
      }
    }
    .camera-filter, .type-filter {
      width: 200px;
      height: 40px;
      font-size: 17px;
    }
    .search-button {
      height: 40px;
      width: 75px;
    }
  }

  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    height: 30px;
    button {
      margin: 0 10px;
      padding: 5px 15px;
      background-color: #409EFF;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }
    button:disabled {
      background-color: #D3D3D3;
      cursor: not-allowed;
    }
  }
}
</style>
